import { Inject, Injectable } from '@nestjs/common';
import { Instance, NacosNamingClient } from 'nacos';
import weightedRandomSelect from './utils/weightedRandomSelect';

@Injectable()
export class NacosNamingClientService {
  private nacosNamingClient:NacosNamingClient;
  constructor(
      @Inject('NacosNamingClient') nacosNamingClient:NacosNamingClient
    ) {
    this.nacosNamingClient = nacosNamingClient
  }

  async getClient(){
    return this.nacosNamingClient
  }

  async selectOneInstances(options:{
    serviceName:string,
    groupName?:string,
    clusters?:string,
    healthy?: boolean, 
    subscribe?: boolean
  }){
    const hosts = await this.nacosNamingClient.selectInstances(
      options.serviceName,
      options.groupName,
      options.clusters,
      options.healthy,
      options.subscribe
    );
    const host = weightedRandomSelect(hosts)
    return host
  }

  async registerInstance(options:{
    serviceName:string,
    instance:Instance,
    groupName?:string
  }){
    await this.nacosNamingClient.registerInstance(
      options.serviceName,
      options.instance,
      options?.groupName
    )
    return this.nacosNamingClient
  }
  
}
